/**
 * 认证控制器
 * 处理用户注册、登录与认证相关业务逻辑
 */
const asyncHandler = require('express-async-handler');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const User = require('../models/user');

// 生成JWT令牌
const generateToken = (id) => {
  return jwt.sign({ id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN || '30d'
  });
};

/**
 * 用户注册
 * @route POST /api/auth/register
 * @access Public
 */
const register = asyncHandler(async (req, res) => {
  const { username, email, password } = req.body;
  
  // 验证输入
  if (!username || !email || !password) {
    res.status(400);
    throw new Error('请提供所有必需字段');
  }
  
  // 检查邮箱是否已被注册
  const emailExists = await User.findOne({ email });
  if (emailExists) {
    res.status(400);
    throw new Error('该邮箱已被注册');
  }
  
  // 检查用户名是否已被使用
  const usernameExists = await User.findOne({ username });
  if (usernameExists) {
    res.status(400);
    throw new Error('该用户名已被使用');
  }
  
  // 创建用户
  const user = await User.create({
    username,
    email,
    password
  });
  
  if (user) {
    // 生成令牌
    const token = generateToken(user._id);
    
    res.status(201).json({
      _id: user._id,
      username: user.username,
      email: user.email,
      avatar: user.avatar,
      token
    });
  } else {
    res.status(400);
    throw new Error('注册失败，请稍后重试');
  }
});

/**
 * 用户登录
 * @route POST /api/auth/login
 * @access Public
 */
const login = asyncHandler(async (req, res) => {
  const { usernameOrEmail, password } = req.body;
  
  // 验证输入
  if (!usernameOrEmail || !password) {
    res.status(400);
    throw new Error('请提供用户名/邮箱和密码');
  }
  
  // 查找用户（支持使用用户名或邮箱登录）
  const user = await User.findOne({
    $or: [
      { username: usernameOrEmail },
      { email: usernameOrEmail }
    ]
  });
  
  // 验证用户和密码
  if (user && (await user.matchPassword(password))) {
    // 更新用户在线状态
    user.isOnline = true;
    user.lastSeen = Date.now();
    await user.save();
    
    // 返回用户数据和令牌
    res.json({
      _id: user._id,
      username: user.username,
      email: user.email,
      avatar: user.avatar,
      token: generateToken(user._id)
    });
  } else {
    res.status(401);
    throw new Error('用户名/邮箱或密码不正确');
  }
});

/**
 * 用户登出
 * @route POST /api/auth/logout
 * @access Private
 */
const logout = asyncHandler(async (req, res) => {
  const user = await User.findById(req.user._id);
  
  if (user) {
    // 更新用户在线状态
    user.isOnline = false;
    user.lastSeen = Date.now();
    await user.save();
    
    res.json({ message: '登出成功' });
  } else {
    res.status(404);
    throw new Error('用户未找到');
  }
});

/**
 * 验证令牌
 * @route GET /api/auth/verify
 * @access Private
 */
const verifyToken = asyncHandler(async (req, res) => {
  res.json({ valid: true, user: req.user });
});

/**
 * 获取当前登录用户信息
 * @route GET /api/auth/me
 * @access Private
 */
const getCurrentUser = asyncHandler(async (req, res) => {
  const user = await User.findById(req.user._id);
  
  if (user) {
    res.json({
      _id: user._id,
      username: user.username,
      email: user.email,
      avatar: user.avatar,
      bio: user.bio,
      isOnline: user.isOnline,
      lastSeen: user.lastSeen,
      createdAt: user.createdAt
    });
  } else {
    res.status(404);
    throw new Error('用户未找到');
  }
});

module.exports = {
  register,
  login,
  logout,
  verifyToken,
  getCurrentUser
}; 